import Cookies from 'js-cookie'
import CookieMap from '@/config/cookieMap'

function getTopLevelDomain() {
  const domainParts = window.location.hostname.split('.')
  if (domainParts.length === 1) {
    return domainParts[0]
  }
  return domainParts.slice(-2).join('.')
}

const topLevelDomain = getTopLevelDomain()

export function getToken(tokenKey = CookieMap.token) {
  return Cookies.get(tokenKey)
}

export function setToken(token, opt = {}) {
  return Cookies.set(CookieMap.token, token, opt)
}

export function setTokenByKey(token, tokenKey = CookieMap.token, opt = {}) {
  return Cookies.set(tokenKey, token, opt)
}

export function removeToken(tokenKey = CookieMap.token) {
  Cookies.remove(tokenKey)
  Cookies.remove(tokenKey, { domain: topLevelDomain })
}
